<template>
  <div class="wrapper" ref="wrapper">
    <div class="scroll-wrap" :style="{ width: wrapWidth }">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  name: "Scroller",
  props: {
    handleToScroll: {
      type: Function,
      default: function() {},
    },
    handleToTouchEnd: {
      type: Function,
      default: function() {},
    },
    scrollX: {
      type: Boolean,
      default: false,
    },
    scrollY: {
      type: Boolean,
      default: true,
    },
    // 接收滚动视图的宽度
    width: {
      type: [String, Number],
      default: "100%",
    },
  },
  computed: {
    // 计算最终宽度的样式
    wrapWidth() {
      if (typeof this.width === "string") {
        return this.width;
      } else {
        return this.width + "px";
      }
    },
  },
  mounted() {
    var scroll = new BScroll(this.$refs.wrapper, {
      tap: true,
      click: true,
      probeType: 3,
      scrollX: this.scrollX,
      scrollY: this.scrollY,
    });
    this.scroll = scroll;
    scroll.on("scroll", (pos) => {
      this.handleToScroll(pos);
    });

    scroll.on("touchEnd", (pos) => {
      this.handleToTouchEnd(pos);
    });
  },
  methods: {
    toScrollTop(y) {
      this.scroll.scrollTo(0, y);
    },
    toScrollLeft(x) {
      this.scroll.scrollTo(x, 0);
    },
  },
};
</script>

<style scoped>
.scroll-wrap {
  width: max-content;
}
.wrapper {
  width: 100%;
}
</style>
